<template>
  <div>
    <el-row>
      <el-col>
      <el-form :model="addressInfo" ref="addressInfo" label-width="55px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="省级">
              <el-select value-key="name" v-model="province" filterable @change="changeAddress(1)">
                <el-option
                  v-for="(item,index) in provinces"
                  :key="item.name+index"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="市级">
              <el-select value-key="name" v-model="city" :disabled="disabledCity" filterable @change="changeAddress(2)">
                <el-option
                  v-for="(item,index) in cities"
                  :key="item.name+index"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="县级">
              <el-select value-key="name" v-model="district" :disabled="disabledDistrict" filterable @change="changeAddress(3)">
                <el-option
                  v-for="(item,index) in districts"
                  :key="item.name+index"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="乡镇">
              <el-select value-key="name" v-model="street" :disabled="disabledStreet" filterable @change="changeAddress(4)">
                <el-option
                  v-for="(item,index) in streets"
                  :key="item.name+index"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="收货人"
              prop="consignee"
              :rules="[{trigger: 'blur', validator: validateConsignee}]">
              <el-input name="consignee" v-model="addressInfo.consignee" placeholder="收货人名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="手机"
              prop="phone"
              :rules="[{trigger: 'blur', validator: validateAddressPhone}]">
              <el-input name="phone" v-model="addressInfo.phone" placeholder="收货人联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="详址"
              prop="address"
              :rules="[{trigger: 'blur', validator: validateAddressInfo}]">
              <el-input name="address" v-model="addressInfo.address" placeholder="收货人详细地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <div style="float: right">
          <el-button @click="addAddressLast">取 消</el-button>
          <el-button type="primary" @click="addressInfoSave">保 存</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import persinalApi from "@/api/personal"
  export default {
    data(){
      return {
        /** 地址信息 **/
        addressInfo:{},
        /** 省级地区数据 **/
        province:{},
        provinces:[],
        /** 市级地区数据 **/
        city:{},
        cities:[],
        disabledCity: true,
        /** 县级地区数据 **/
        district:{},
        districts:[],
        disabledDistrict: true,
        /** 乡镇级地区数据 **/
        street:{},
        streets:[],
        disabledStreet: true,
      }
    },
    created(){
      this.initPage();
    },
    methods: {
      initPage(){
        let params = {
          keywords: "100000",
          subdistrict: 1
        }
        this.addressInfo = {};
        this.province = {};
        this.provinces = [];
        this.city = {};
        this.cities = [];
        this.district = {};
        this.districts = [];
        this.street = {};
        this.streets = [];
        this.disabledCity = true;
        this.disabledDistrict = true;
        this.disabledStreet = true;
        persinalApi.getAddressInfo(params).then(res => {
          this.addressDialogVisible = true;
          this.provinces = res.data.districts[0].districts;
        }).catch(() => {
          this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
        });
      },
      /** 地址信息收货人名称校验 **/
      validateConsignee(rule, value, callback){
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入联系人名称'));
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('名称只能由常用汉字+英文字母+数字组成'));
        } else {
          callback()
        }
      },
      validateAddressInfo(rule, value, callback){
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入详细地址'));
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('详细地址只能由常用汉字+英文字母+数字组成'));
        } else {
          callback()
        }
      },
      /** 地址信息收货人手机号校验 **/
      validateAddressPhone(rule, value, callback){
        const usernameRegex = /^1[34578]\d{9}$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入手机号码'))
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      addressSelectStruts(level, data){
        /** 状态赋值初始化 **/
        if (level == "province"){
          this.provinces = data;
        } else if (level == "city"){
          this.cities = data;
          this.disabledCity = false;
        } else if (level == "district"){
          this.districts = data;
          this.disabledDistrict = false;
        } else if (level == "street"){
          this.streets = data;
          this.disabledStreet = false;
        }
      },
      addressSelectInitStruts(level){
        /** 状态清理旧值 **/
        let levelCode = 0
        switch (level) {
          case 1:
            this.city = {};
            this.cities = [];
            this.district = {};
            this.districts = [];
            this.street = {};
            this.streets = [];
            this.disabledCity = true;
            this.disabledDistrict = true;
            this.disabledStreet = true;
            levelCode = this.province.adcode;
            break;
          case 2:
            this.district = {};
            this.districts = [];
            this.street = {};
            this.streets = [];
            this.disabledDistrict = true;
            this.disabledStreet = true;
            levelCode = this.city.adcode;
            break;
          case 3:
            this.street = {};
            this.streets = [];
            this.disabledStreet = true;
            levelCode = this.district.adcode
            break;
          case 4:
            levelCode = this.streets.adcode;
            break;
        }
        return levelCode;
      },
      /** 选择地区事件 **/
      changeAddress(level){
        if (level<1 || level > 3){
          /** 街道级别没有下级就直接返回 **/
          return true;
        }
        let params = {
          keywords: this.addressSelectInitStruts(level),
          subdistrict: 1
        }
        persinalApi.getAddressInfo(params).then(res => {
          this.addressSelectStruts(res.data.districts[0].districts[0].level, res.data.districts[0].districts);
          return true;
        }).catch(() => {
          this.$notify.error({title: '失败', message: "地址信息获取失败"});
        });
      },
      /** 取消事件 **/
      addAddressLast(){
        this.$emit('addressLast');
      },
      /** 地区信息保存事件 **/
      addressInfoSave(){
        if (typeof(this.street.adcode) === "undefined" || this.street.adcode === ""){
          this.$notify({title: '提示', message: "地址信息请选择到乡镇级", type: 'warning'});
          return false;
        }
        this.$refs['addressInfo'].validate(valid => {
          if (valid) {
            let params = {
              id: typeof(this.addressInfo.id)=="undefined"?null:this.addressInfo.id,
              consignee: this.addressInfo.consignee,
              phone: this.addressInfo.phone,
              address: this.addressInfo.address,
              province: this.province.adcode,
              provinceName: this.province.name,
              city: this.city.adcode,
              cityName: this.city.name,
              district: typeof(this.district.adcode)=="undefined"?null:this.district.adcode,
              districtName: typeof(this.district.adcode)=="undefined"?null:this.district.name,
              street: this.street.adcode,
              streetName: this.street.name
            }
            persinalApi.saveAddressInfo(params).then(res => {
              if (res.code === 1){
                this.$notify({title: '成功', message: "收货地址信息保存成功", type: 'success'});
                this.$emit('addressSuccess');
              }
            }).catch(() => {
              this.$notify.error({title: '失败', message: "地址信息保存失败"});
              return false;
            })
          } else {
            this.$notify({title: '提示', message: "输入的信息不合规", type: 'warning'});
          }
        })
      }
    }
  }
</script>

<style>
</style>
